package net.muchine.web.front.controller;

import java.util.Locale;
import java.util.ResourceBundle;

import net.muchine.core.domain.user.Preference.DisplayComments;
import net.muchine.core.domain.user.Preference.EmailNotification;
import net.muchine.web.common.Messages;
import net.muchine.web.front.session.UserSession;
import net.muchine.web.support.Codes;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

public abstract class BaseController {
	@Autowired protected Validator validator;
	
	@Autowired protected UserSession session;
	@Autowired protected Codes codes;
	
	protected Log log = LogFactory.getLog(this.getClass());
	
	// NOTE: This method should be used only for unit testing. Do not inject session directly.
	public void setUserSession(UserSession session) {
		this.session = session;
	}
	
	@InitBinder
	public void initLocalValidator(WebDataBinder dataBinder) {
		dataBinder.setValidator(validator);
	}
	
	public ResourceBundle getResourceBundle(Locale locale) {
		return ResourceBundle.getBundle("properties/messages", locale);
	}
	
	protected void setAccountCodeLists(ModelMap model) {
		model.put("language", codes.getLanguageList());
		model.put("timeZoneList", codes.getTimeZoneList());
		model.put("displayComments", DisplayComments.getMap());
		model.put("emailNotification", EmailNotification.getMap());
	}
	
	protected void logErrors(BindingResult result) {
		log.info("error count: " + result.getErrorCount());
		for (ObjectError error : result.getAllErrors()) {
			if (FieldError.class.isAssignableFrom(error.getClass()))
				log.info(error.getCode() + "." + error.getObjectName() + "." + ((FieldError) error).getField());
			else
				log.info(error.getCode() + "." + error.getObjectName());			
		}
	}
	
	protected void setSuccessCreationNotice(ModelMap model, Locale locale) {
		model.put(Messages.NOTICE,
				this.getResourceBundle(locale).getString("Success.creation"));
	}
}
